package com.bupt.godxian.charging.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bupt.godxian.charging.config.CommonResponse;
import com.bupt.godxian.charging.entity.ChargeRecord;
import com.bupt.godxian.charging.entity.ChargeRequest;
import com.bupt.godxian.charging.entity.Charger;
import com.bupt.godxian.charging.entity.User;
import com.bupt.godxian.charging.entity.dto.ChargerStatus;
import com.bupt.godxian.charging.mapper.*;
import com.bupt.godxian.charging.util.Timer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminService {

    private final ChargerMapper chargerMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ChargeRecordMapper chargeRecordMapper;

    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private ChargeRequestMapper chargeRequestMapper;


    @Autowired
    public AdminService( ChargerMapper chargerMapper) {
        this.chargerMapper = chargerMapper;

    }
    //charge service
    public List<Charger> findChargeOrder() {
        return chargerMapper.findAllorder();
    }

    //处理，获取充电站的数据报表列表
    public CommonResponse query_report(){
        Timer timer =new Timer();
        //读取数据库
        List<Charger> chargerList = chargerMapper.selectList(null);
        //用报表计算结果
        boolean success=true ;
        String error_msg = null;
        List<Map<String, Object>> reportList = new ArrayList<>();
        if (chargerList.isEmpty()){
            success=false;
            error_msg="没有充电桩";
        }else {

            for (Charger charger : chargerList) {
                long passSecondsFromStart = timer.getCurTimestamp() - charger.getStartTime();
                //从 ChargeRecord 表中获取与指定 charger.id 匹配的记录，并计算 charging_cost、service_cost 和 total_cost 列的总和。
                Map<String, Object> chargerFee = chargeRecordMapper.getChargerFee(Long.valueOf(charger.getId()));

                Map<String, Object> report = new HashMap<>();
                report.put("day", BigDecimal.valueOf(passSecondsFromStart)
                        .divide(BigDecimal.valueOf(86400), 0, RoundingMode.CEILING).intValue());
                report.put("week", BigDecimal.valueOf(passSecondsFromStart)
                        .divide(BigDecimal.valueOf(604800), 0, RoundingMode.CEILING).intValue());
                report.put("month", BigDecimal.valueOf(passSecondsFromStart)
                        .divide(BigDecimal.valueOf(2592000), 0, RoundingMode.CEILING).intValue());
                report.put("pile_id", charger.getId());
                report.put("cumulative_usage_times", charger.getCumulativeUsageTimes());
                report.put("cumulative_charging_time", charger.getCumulativeChargingTime());
                report.put("cumulative_charging_amount", charger.getCumulativeChargingAmount());
                report.put("cumulative_charging_earning", chargerFee != null ? chargerFee.get("t_charging_cost") : BigDecimal.ZERO);
                report.put("cumulative_service_earning", chargerFee != null ? chargerFee.get("t_service_cost") : BigDecimal.ZERO);
                report.put("cumulative_earning", chargerFee != null ? chargerFee.get("t_total_cost") : BigDecimal.ZERO);

                reportList.add(report);
            }

        }
        if (success){
            return new CommonResponse(0, "Success",reportList);
        }else return new CommonResponse(-1, error_msg);




    }
    //获取目前所有正在排队的用户
    public CommonResponse query_queue() {

        List<ChargeRequest> userInQueue = chargeRequestMapper.getUserInQueue();
        Timer timer = new Timer();

        boolean success = true;
        String error_msg = null;
        List<Map<String, Object>> queueList = new ArrayList<>();
        if (userInQueue == null || userInQueue.isEmpty()) {
            success = false;
            error_msg = "没有正在排队的用户";
        } else {
            for (ChargeRequest user : userInQueue) {
                BigDecimal waitingTime = BigDecimal.valueOf(timer.getCurTimestamp()).subtract(user.getRequestSubmitTime());

                Map<String, Object> queueItem = new HashMap<>();
                queueItem.put("pile_id", user.getChargePileId());

                // 使用MyBatis-Plus执行查询，获取username
                String username = userMapper.selectOne(new QueryWrapper<User>().select("username").eq("id", user.getUserId())).getUsername();
                queueItem.put("username", username);

                queueItem.put("battery_size", String.format("%.2f", user.getBatterySize()));
                queueItem.put("require_amount", String.format("%.2f", user.getRequireAmount()));
                queueItem.put("waiting_time", waitingTime);

                // 将每个元素添加到queueList中
                queueList.add(queueItem);
            }

        }
        if (success) {
            return new CommonResponse(0, "Success", queueList);
        } else
            return new CommonResponse(-1, error_msg);

    }
        //处理，更新充电桩状态
        public CommonResponse update_pile(String pileId, ChargerStatus status){
            boolean success = false;
            String error_msg = null;

            Charger charger = chargerMapper.selectById(pileId);
            if (charger == null ) {
                // 充电桩不存在
                error_msg = "充电桩不存在";
            } else {
                boolean change = false;

                if (!charger.getChargerStatus().equals(status)) {
                    change = true;
                    if (status.equals((ChargerStatus.RUNNING))) {
                        Timer timer = new Timer();
                        charger.setChargerStatus(status);
                        charger.setStartTime(timer.getCurTimestamp());
                    } else {
                        charger.setChargerStatus(status);
                    }
                    chargerMapper.updateById(charger);
                }

                // 触发调度
                if (change && status.equals(ChargerStatus.RUNNING)) {
                    scheduleService.schedule(3, null, charger.getType(),null,false,false);
                } else if (change) {
                    scheduleService.schedule(4, null, null, Long.valueOf(pileId),false,false);
                }
            }

            if (success) {
                return new CommonResponse(0, "Success");
            } else return new CommonResponse(-1, error_msg);

        }


    }
